package com.cn.server.module.player.handler.wsPlayerHandler;

import com.cn.common.core.exception.ErrorCodeException;
import com.cn.common.core.model.ResultCode;
import com.cn.common.core.model.websocket.HttpResult;
import com.cn.common.core.session.Session;
import com.cn.common.module.platform.PlatformType;
import com.cn.common.module.player.response.PlayerResponse;
import com.cn.common.module.player.websocket.PlayerHttpResponse;
import com.cn.common.module.player.websocket.PlayerHttpRequest;
import com.cn.common.utils.GsonHelperUtils;
import com.cn.server.module.player.dao.entity.Player;
import com.cn.server.module.player.service.PlayerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 玩家模块
 * @author -jiawuwei-
 *
 */
@Component
public class WSPlayerHandlerImpl implements WSPlayerHandler {
	
	@Autowired
	private PlayerService playerService;

	@Override
	public HttpResult<PlayerHttpResponse> registerAndLogin(Session session, String data) {
		
		PlayerHttpResponse result = null;
		try {
			//将data格式化
			PlayerHttpRequest playerHttpRequest = GsonHelperUtils.fromJson(data, PlayerHttpRequest.class);


			//参数判空
			if(StringUtils.isEmpty(playerHttpRequest.getPlayerName()) || StringUtils.isEmpty(playerHttpRequest.getPassward())){
				return HttpResult.ERROR(ResultCode.PLAYERNAME_NULL);
			}
			
			//执行业务
			Player player = new Player();
			player.setPlayerName(playerHttpRequest.getPlayerName());
			player.setPassward(playerHttpRequest.getPassward());
			result = playerService.registerAndLogin(session, player);
		} catch (ErrorCodeException e) {
		    e.printStackTrace();
			return HttpResult.ERROR(e.getErrorCode());
		} catch (Exception e) {
			e.printStackTrace();
			return HttpResult.ERROR(ResultCode.UNKOWN_EXCEPTION);
		}
		return HttpResult.SUCCESS(result);
	}

	@Override
	public HttpResult<PlayerHttpResponse> login(Session session, String data) {
		PlayerHttpResponse result = null;
		try {
			//将data格式化
			PlayerHttpRequest playerHttpRequest = GsonHelperUtils.fromJson(data, PlayerHttpRequest.class);
			
			//参数判空
			if(StringUtils.isEmpty(playerHttpRequest.getPlayerName()) || StringUtils.isEmpty(playerHttpRequest.getPassward())){
				return HttpResult.ERROR(ResultCode.PLAYERNAME_NULL);
			}
			
			//执行业务
			Player player = new Player();
			player.setPlatType(PlatformType.FROM_BROSWER);
			player.setPlayerName(playerHttpRequest.getPlayerName());
			player.setPassward(playerHttpRequest.getPassward());
			result = playerService.login(session, player);
		} catch (ErrorCodeException e) {
            e.printStackTrace();
			return HttpResult.ERROR(e.getErrorCode());
		} catch (Exception e) {
			e.printStackTrace();
			return HttpResult.ERROR(ResultCode.UNKOWN_EXCEPTION);
		}
		return HttpResult.SUCCESS(result);
	}

}
